var myhref = window.location.host;
var serverURL = "https://"+myhref+'/';


var resourceURL = serverURL;
var ajaxjsURL = "http://www.qsdjf.net/";

var accountURL='http://account.qsdjf.net/';

var  activityURL='http://activity.qsdjf.net/';

var Tools=function () {
	// 工具类
	var self=this;
	//个人中心 点击最近投资  进入详情页
	self.centerXQ=ajaxjsURL+'product/detail/';
	//我的投资界面   合同
	self.investHt=accountURL+'api/contract/view?orderNumber=';
	
	//去投资
	self.goInvest=ajaxjsURL+"/list.html?category=-1";


	//接口
	self.apiURL={
		queryUserInfo:'api/user/queryUserInfo.do',//用户信息
		getServerTime:'api/common/getServerTime?t=' + new Date(),//服务器时间
		queryAccountInfo:'api/custody/account/queryAccountInfo.go',//资金账户信息
		queryOrderPage:'api/user/order/queryOrderPage.do',//投资信息
		bankCard:'api/custody/bankCard.do',//获取银行卡信息
		buildActivateStockedUserParms:'api/custody/account/buildActivateStockedUserParms.do',//用户激活
		queryInvestPage:'api/user/order/queryInvestPage.do',//查询投资记录
		redEnvelopeList:'api/redEnvelope/list.do',//用户红包列表
		interestCouponList:'api/interestCoupon/list',//用户加息券列表
		rechargeLog:'api/custody/account/rechargeLog.do',//充值记录
		withdrawLog:'api/custody/account/withdrawLog.do',//提现记录
		queryFundPage:'api/custody/account/queryFundPage.do',//资金流水
		buildChangeBankcardParms:'api/custody/bankCard/buildChangeBankcardParms.do',//添加银行卡
		buildRechargeParms:'api/custody/recharge/buildRechargeParms.do', //快捷/网银 充值
		buildWithdrawParms:'api/custody/withdraw/buildWithdrawParms.do',//提现
		inviteList:'api/user/inviteList',//推荐结果
		testResult:'api/risk/testResult.do',//测试结果
		updateUserPwd:'api/safety/updateUserPwd.do',//修改登录密码
		testSubmit:'api/risk/testSubmit.do',//测试提交
		tradePasswordExists:'api/user/safety/tradePasswordExists.do',//是否存在交易密码
		buildResetPasswordParms:'api/safety/buildResetPasswordParms.do',//交易密码修改
		contractView:'api/contract/view',//合同,
		buildUnbindBankcardParms:'api/custody/bankCard/buildUnbindBankcardParms.do',//银行卡解绑
		buildOpenAccountParms:'api/custody/account/buildOpenAccountParms.do'//开户
	};
	self.isOpenAccount=function () {
		//获取基本信息 判断是否开户
		self.doGet(accountURL+self.apiURL.queryUserInfo,{},function (data) {
			if(data.status==0){
				if(data.data.custodyStatus=='111'||data.data.custodyStatus==111){
					$('body').after('<div class="pop_error_oa goOpenAccount"><p class="pop_error_oa error_oa"></p> <div class="pop_oa"> <a href="javascript:;" class="pop_op1 openToShanghai">存管开户</a> </div> </div>');
				}else if(data.data.custodyStatus=='0'||data.data.custodyStatus==0){
					$(document).on("click", ".toRecharge,.toWithdraw,.toBank", function () {
						$('body').after('<div class="pop_error_oa goOpenAccount"><p class="pop_error_oa error_oa"></p> <div class="pop_oa"> <div > <a href="javascript:;" class="pop_op openAccount_open">存管开户</a> <p class="pop_fg"></p> <a href="javascript:;" class="pop_wait openAccount_close">以后再说</a> </div> </div> </div>');
					});
				}else{
					//获取银行卡信息
					self.doGet(accountURL+self.apiURL.bankCard,{},function (datas) {
						if(datas.data!=null){
							$('.toBank').attr('href','bankcard.html');
							$('.toRecharge').attr('href','recharge.html?tag=recharge');
							$('.toWithdraw').attr('href','recharge.html?tag=withdrawals');
						}else{
							$('.toBank,.toRecharge,.toWithdraw').attr('href','bankcard.html');
						}
					});

				}
			}
		});

		$(document).on("click", ".openToShanghai", function (data) {
			self.doPost(accountURL+self.apiURL.buildActivateStockedUserParms,{},function (data) {
				if(data.status==0){
					self.formPost(data.data.actionUrl, data.data.parms);
				}
			})
		});
		//开户弹窗   点击俩按钮
		$(document).on("click", ".openAccount_open", function () {
			$('.openAccount_open').attr('href', 'openAccount.html')
		});
		$(document).on("click", ".openAccount_close", function () {
			$('.goOpenAccount').hide();
		});
	};

	self.doPost=function(url,data,cb){
		 
		var _this = this;
		$.ajax({
			url:url+'?='+Math.random(),
			type:'POST',
			data:data,
			crossDomain: true,
			xhrFields: {
				withCredentials: true
			},
			beforeSend: function(xhr) {
				xhr.setRequestHeader("from", "pc");
				xhr.setRequestHeader("timestamp", getNowFormatDate());
				xhr.setRequestHeader("version",'1.1.6');
				xhr.withCredentials = true;
			},
			success:function(data){
				cb(data);
			}
		});
	};
	self.doGetJsonp=function(url,data,cb){
		var _this = this;
		$.ajax({
			url:url,
			dataType:"jsonp",
			data:data,
			crossDomain: true,
			xhrFields: {
				withCredentials: true
			},
			beforeSend: function(xhr) {
				xhr.setRequestHeader("from", "pc");
				xhr.setRequestHeader("timestamp", getNowFormatDate());
				xhr.setRequestHeader("version",'1.1.6');
				xhr.withCredentials = true;
			},
			jsonp:"jsonpcallback",
			success:function(data){
				cb(data);
			}
		});
	};

	/**
	 * ajax get
	 * @param url(String)
	 * @param data(Json) 需要提交的数据
	 * @param cb(Function) 回调函数
	 */
	self.doGet = function(uri,data,cb){
		var _this = this;
		var url = uri + '?';
		if(data){
			url += $.map(data,function(n,i){
				if(i == data.length-1){
					return i+'='+n;
				}else{
					return i+'='+n+'&';
				}
			}).join('');
		}

		$.ajax({
			url:url,
			type:'GET',
			crossDomain: true,
			xhrFields: {
				withCredentials: true
			},
			beforeSend: function(xhr) {
				xhr.setRequestHeader("from", "pc");
				xhr.setRequestHeader("timestamp", getNowFormatDate());
				xhr.setRequestHeader("version",'1.1.6');
				xhr.withCredentials = true;
			},
			success:function(data){
				cb(data);
			}
		});
	};
	/**
	 * 页面跳转util
	 * @param uri (String)
	 * @param params (Json)
	 */
	self.skip = function(uri,params){
		var url = uri + '?',
			time = 0.3;

		if(params){
			url += $.map(params,function(n,i){
				return n;
			}).join('');
		}
		if(uri){
			$('html').addClass('skipurl').css({'transition':'all '+time+'s ease-in-out','-webkit-transition':'all '+time+'s ease-in-out','-moz-transition':'all '+time+'s ease-in-out','-o-transition':'all '+time+'s ease-in-out'})
			var oTime = time*1000;

			setTimeout(function(){
				window.location.href = resourceURL+url;
			},oTime)
		}
	};
	self.cpzcSkip=function(uri,params){
		var url = uri,
			time = 0.3;
		if(params){
			url += $.map(params,function(n,i){
				return n;
			}).join('');
		}
		if(uri){
			$('html').addClass('skipurl').css({'transition':'all '+time+'s ease-in-out','-webkit-transition':'all '+time+'s ease-in-out','-moz-transition':'all '+time+'s ease-in-out','-o-transition':'all '+time+'s ease-in-out'})
			var oTime = time*1000;

			setTimeout(function(){
				window.location.href = resourceURL+url;
			},oTime)
		}
	};
 
	self.setCookie=function(cname, cvalue, seconds){
		var d = new Date();
		d.setTime(d.getTime()+(seconds*1000));
		var expires = "expires="+d.toGMTString();
		document.cookie = cname + "=" + cvalue + "; " + expires+ ";path=/";
	};
	self.getCookie =function(cname){
		var name = cname + "=";
		var ca = document.cookie.split(';');
		for(var i=0; i<ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1);
			if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
		}
		return "";
	};
	self.removeCookie = function(cname){
		var exp = new Date();
		exp.setTime(exp.getTime() - 1);
		document.cookie = cname + "=; expires=" + exp.toGMTString();
	};
	self.getParam=function(name){
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
		var r = window.location.search.substr(1).match(reg);
		if (r!=null) return (r[2]);
		return null;
	};
	/*判断对象是否有内容*/
	self.isEmptyObject=function(obj) {
		for (var key in obj) {
			return false;
		}
		return true;
	};

	/*添加url跳转特效*/
	self.urlSkip= function(className,url) {
		var othis = $(className),
			time = 0.3;
		othis.on('click', function () {
			window.location.href = resourceURL + url;
		})
	};
	self.accordSkip= function(url){
		time = 0.3;
		$('html').addClass('skipurl').css({'transition':'all '+time+'s ease-in-out','-webkit-transition':'all '+time+'s ease-in-out','-moz-transition':'all '+time+'s ease-in-out','-o-transition':'all '+time+'s ease-in-out'})
		var oTime = time*1000;
		setTimeout(function(){
			window.location.href = url;
		},oTime)
	};
	self.strComma=function(num){
		var oNum = num.toString();
		var strComma = oNum.split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(/\,$/, '').split('').reverse().join('');
		return strComma;
	};

	/*上传当前时间*/
	self.getNowFormatDate =function() {
		var date = new Date();
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var strDate = date.getDate();

		var hours =date.getHours();
		var minutes = date.getMinutes();
		var seconds  = date.getSeconds();

		if (month >= 1 && month <= 9) {month = "0" + month;}
		if (strDate >= 0 && strDate <= 9) {strDate = "0" + strDate;}
		if (hours >= 0 && hours <= 9) {hours = "0" + hours;}
		if (minutes >= 0 && minutes <= 9) {minutes = "0" + minutes;}
		if (seconds >= 0 && seconds <= 9) {seconds = "0" + seconds;}
		var currentdate = year + month + strDate + hours + minutes +seconds;
		return currentdate;
	};

	/**value:20001212*/
	self.formatStringyyyyMMddToyyyy_MM_dd =function(value){
		if(value.length == 14 || value.length == 14){
			return value.substring(0, 4) + "-" + value.substring(4, 6) + "-" + value.substring(6, 8) + "  " + value.substring(8, 10) + ":" + value.substring(10, 12) + ':' + value.substring(12, 14);
		} else if(value.length == 8){
			return value.substring(0, 4) + "-" + value.substring(4, 6) + "-" + value.substring(6, 8);
		} else if(value.length == 6){
			return value.substring(0, 4) + "-" + value.substring(4, 6);
		} else {
			return value;
		}
	};
	self.luhmCheck=function (bankno){
		var lastNum=bankno.substr(bankno.length-1,1);//取出最后一位（与luhm进行比较）

		var first15Num=bankno.substr(0,bankno.length-1);//前15或18位
		var newArr=new Array();
		for(var i=first15Num.length-1;i>-1;i--){    //前15或18位倒序存进数组
			newArr.push(first15Num.substr(i,1));
		}
		var arrJiShu=new Array();  //奇数位*2的积 <9
		var arrJiShu2=new Array(); //奇数位*2的积 >9

		var arrOuShu=new Array();  //偶数位数组
		for(var j=0;j<newArr.length;j++){
			if((j+1)%2==1){//奇数位
				if(parseInt(newArr[j])*2<9)
					arrJiShu.push(parseInt(newArr[j])*2);
				else
					arrJiShu2.push(parseInt(newArr[j])*2);
			}
			else //偶数位
				arrOuShu.push(newArr[j]);
		}

		var jishu_child1=new Array();//奇数位*2 >9 的分割之后的数组个位数
		var jishu_child2=new Array();//奇数位*2 >9 的分割之后的数组十位数
		for(var h=0;h<arrJiShu2.length;h++){
			jishu_child1.push(parseInt(arrJiShu2[h])%10);
			jishu_child2.push(parseInt(arrJiShu2[h])/10);
		}

		var sumJiShu=0; //奇数位*2 < 9 的数组之和
		var sumOuShu=0; //偶数位数组之和
		var sumJiShuChild1=0; //奇数位*2 >9 的分割之后的数组个位数之和
		var sumJiShuChild2=0; //奇数位*2 >9 的分割之后的数组十位数之和
		var sumTotal=0;
		for(var m=0;m<arrJiShu.length;m++){
			sumJiShu=sumJiShu+parseInt(arrJiShu[m]);
		}

		for(var n=0;n<arrOuShu.length;n++){
			sumOuShu=sumOuShu+parseInt(arrOuShu[n]);
		}

		for(var p=0;p<jishu_child1.length;p++){
			sumJiShuChild1=sumJiShuChild1+parseInt(jishu_child1[p]);
			sumJiShuChild2=sumJiShuChild2+parseInt(jishu_child2[p]);
		}
		//计算总和
		sumTotal=parseInt(sumJiShu)+parseInt(sumOuShu)+parseInt(sumJiShuChild1)+parseInt(sumJiShuChild2);

		//计算Luhm值
		var k= parseInt(sumTotal)%10==0?10:parseInt(sumTotal)%10;
		var luhm= 10-k;

		if(lastNum==luhm){
			return true;
		} else{
			return false;
		}
	};
	/*登录顶部*/

	self.getUserInfo = function(userId,permit){
	    self.doPost(accountURL+self.apiURL.queryUserInfo,null,function(data){
	        var html = ''; 
	        if(data.status=='0'){
	            html += ' <li class="jsWeixin"><i class="weixin"></i>微信<span>|</span>'+
                        '<div class="weixinImg"></div></li><li><a href="'+resourceURL+'/about/faq.html" target="_blank">帮助中心</a><span>|</span></li>'+
                        '<li>欢迎<a href="'+resourceURL+'/member/index.html" class="aGreen" rel="nofollow">'+data.data.username+'</a> 来到钱时代金服！'+
                        '<a href="'+resourceURL+'/login/logout.html" rel="nofollow">[退出]</a><span>|</span></li>';
	        }else{
	            html +=' <li class="jsWeixin"><i class="weixin"></i>微信<span>|</span><div class="weixinImg"></div>'+
                        '</li><li><a href="'+resourceURL+'/about/faq.html" target="_blank">帮助中心</a><span>|</span></li>'+
                        '<li><a href="'+resourceURL+'/register.html">注册</a>-<a href="'+resourceURL+'/login.html">登录</a><span>|</span></li>';
	        }
	        $('.user_status').hide().append(html).fadeIn("slow");
	        $(".jsWeixin").hover(function(){
              $(this).addClass("showCss");
            },function(){
              $(this).removeClass("showCss");
            })
	    })
	};
	self.formPost=function (URL, PARAMS) {
		PARAMS = PARAMS || {};
		var temp = document.createElement("form");
		temp.acceptCharset = "utf-8";
		var params = URL.split(/[\?\&]/).slice(1);
		temp.action = URL.split('?')[0];
		temp.method = "post";
		temp.style.display = "none";

		for (var i = 0, len = params.length; i < len; i++) {
			var item = params[i].split('=');
			PARAMS[item[0]] = item[1];
		}
		for (var x in PARAMS) {
			var opt = document.createElement("textarea");
			opt.name = x;
			opt.value = PARAMS[x];
			temp.appendChild(opt);
		}
		document.body.appendChild(temp);
		temp.submit();
		return temp;
	};

	return self;
};
 